<?php

namespace App\Game;

use Carbon\Carbon;
use App\Game\Traits\VrTrait;
use App\Models\OddsHandicap;
use App\Models\Def\MainGamePlat;

class vr extends Game
{
    use VrTrait;

    public $timezone = 'UTC';
    private $platName = 'vr';


    const CREATEUSER = '/Account/CreateUser';
    const LOGIN = '/Account/LoginValidate';
    const TRANSACTION = '/UserWallet/Transaction';
    const KICKUSER = '/Account/KickUser';
    const TRANSACTIONRECORD = '/UserWallet/TransactionRecord';
    const BALANCE = '/UserWallet/Balance';
    const BETRECORD = '/MerchantQuery/Bet';

    public function __construct()
    {
        $this->adds = [
            'main_game_plat_code' => $this->platName,
        ];
    }

    public function getLength()
    {
        return $this->length;
    }

    public function getPre()
    {
        return $this->pre;
    }

    /**
     * gameapi
     * 2018/9/19 16:15
     * Administrator
     * __get
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->$key;
    }

    public function __set($key, $value)
    {
        $this->$key = $value;
    }

    //获取最近更新时间
    public function lastSynchronizedGameFlowTimeStamp()
    {
        if (!$this->lastSynchronizeTime && \Storage::exists('VR_synchronizedTimestamp')) {
            $this->lastSynchronizeTime = \Storage::get('VR_synchronizedTimestamp');
        }

        if (!$this->lastSynchronizeTime && !\Storage::exists('VR_synchronizedTimestamp')) {
            $this->lastSynchronizeTime = time() - $this->start * 60;
        }
        return $this->lastSynchronizeTime;
    }

    // 加密
    private function apiEncode($data)
    {
        $cipher = 'AES-256-ECB';
        $encData = openssl_encrypt($data, $cipher, $this->key, OPENSSL_RAW_DATA);
        return base64_encode($encData);
    }

    // 解密
    private function apiDecode($base64_data)
    {
        $data = base64_decode($base64_data);
        $cipher = 'AES-256-ECB';
        $plain_data = openssl_decrypt($data, $cipher, $this->key, OPENSSL_RAW_DATA);
        return $plain_data;
    }

    public function curlCreateMember($accountUserName, $password, $request)
    {
        $url = $this->gameUrl . self::CREATEUSER;
        $data = ["playerName" => $accountUserName];
        $body = ["version" => $this->version, "id" => $this->merchatId, "data" => $this->apiEncode(json_encode($data))];
        $output = $this->request('POST', $url, $body);
        $output = json_decode($this->apiDecode($output), true);

        if (isset($output['errorCode']) && $output['errorCode'] == 0) {
            return ['success' => true, 'data' => ['accountUserName' => $accountUserName, 'password' => $password], 'message' => ''];
        } else {
            return ['success' => false, 'data' => [], 'message' => '创建失败'];
        }
    }


    //获取余额
    public function curlGetBalance($accountUserName)
    {
        $url = $this->gameUrl . self::BALANCE;

        $data = ["playerName" => $accountUserName];

        $body = ["version" => $this->version, "id" => $this->merchatId, "data" => $this->apiEncode(json_encode($data))];
        $output = $this->request('POST', $url, $body);
        $output = json_decode($this->apiDecode($output), true);
        if (isset($output['balance']) && $output['balance'] != '-1') {
            return ['success' => true, 'data' => ['balance' => $output['balance']], 'message' => ''];
        } else {
            return ['success' => false, 'data' => [], 'message' => '查询失败'];
        }
    }

    //转入游戏

    public function curlTransferIn($accountUserName, $price, $transferid)
    {
        $data = [
            'serialNumber' => $transferid,
            'createTime' => gmdate("Y-m-d\TH:i:s\Z"),
            'amount' => $price,
            'playerName' => $accountUserName,
            'type' => 0
        ];

        $body = [
            "version" => $this->version,
            "id" => $this->merchatId,
            "data" => $this->apiEncode(json_encode($data))
        ];

        $url = $this->gameUrl . self::TRANSACTION;

        $output = $this->request('POST', $url, $body);
        $output = json_decode($this->apiDecode($output), true);

        if (isset($output['state'])) {
            if ($output['state'] == 0) {
                return ['success' => true, 'data' => ['transferid' => $output['serialNumber'], 'transfer_state' => 1], 'message' => ''];
            } else {
                return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '转帐失败'];
            }
        } else {
            return ['success' => false, 'data' => ['transfer_state' => -1], 'message' => '转帐未知'];
        }
    }

    //转出游戏
    public function curlTransferTo($accountUserName, $price, $transferid)
    {
        $data = [
            'serialNumber' => $transferid,
            'createTime' => gmdate("Y-m-d\TH:i:s\Z"),
            'amount' => $price,
            'playerName' => $accountUserName,
            'type' => 1
        ];

        $body = [
            "version" => $this->version,
            "id" => $this->merchatId,
            "data" => $this->apiEncode(json_encode($data))
        ];

        $url = $this->gameUrl . self::TRANSACTION;

        $output = $this->request('POST', $url, $body);
        $output = json_decode($this->apiDecode($output), true);

        if (isset($output['state'])) {
            if ($output['state'] == 0) {
                return ['success' => true, 'data' => ['transferid' => $output['serialNumber'], 'transfer_state' => 1], 'message' => ''];
            } else {
                return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '转帐失败'];
            }
        } else {
            return ['success' => false, 'data' => ['transfer_state' => -1], 'message' => '转帐未知'];
        }
    }

    //查询订单状态
    public function curlCheckTransfer($request)
    {
        return ['success' => false, 'data' => ['transfer_state' => -1], 'message' => '此平台暂无此功能'];
    }

    //踢线
    public function curlKick($accountUserName)
    {
        $data = [
            'playerName' => $accountUserName,
        ];

        $body = [
            "version" => $this->version,
            "id" => $this->merchatId,
            "data" => $this->apiEncode(json_encode($data))
        ];

        $url = $this->gameUrl . self::KICKUSER;

        $output = $this->request('POST', $url, $body);
        $output = json_decode($this->apiDecode($output), true);

        if (isset($output['errorCode'])) {
            if ($output['errorCode'] == 0) {
                return ['success' => true, 'data' => [], 'message' => ''];
            } else {
                return ['success' => false, 'data' => [], 'message' => '踢线失败：' . $output['errorCode']];
            }
        } else {
            return ['success' => false, 'data' => [], 'message' => '请求平台失败，状态未知'];
        }

    }

    //进入游戏
    public function curlJoinGame($request)
    {
        $accountUserName = $request->input('accountUserName');
        $gamecode = $request->input('gamecode', '');

        $mainGamePlat = MainGamePlat::where('main_game_plat_code', $request->mainGamePlat)->first();
        if (isset($request->odds_handicap)) {
            $oddType = OddsHandicap::where([
                    ['code', '=', $request->odds_handicap],
                    ['plat_id', '=', $mainGamePlat->id],
                ]
            )->first();
        }
        $playerOdds = isset($oddType) ? $oddType->odds_value : '';  //赔率
        $url = $this->gameUrl . self::LOGIN;

        $data = '';
        if (empty($playerOdds)) {
            $data = "playerName=" . $accountUserName . "&loginTime=" . gmdate("Y-m-d\TH:i:s\Z");
        } else {
            $data = "playerName=" . $accountUserName . "&loginTime=" . gmdate("Y-m-d\TH:i:s\Z") . '&playerOdds=' . $playerOdds;
        }
        if (!empty($gamecode)) {
            $data .= '&channelId=' . $gamecode;
        }
        $encrypt_data = urlencode($this->apiEncode($data));
        $loginUrl = $url . "?version=" . $this->version . "&id=" . $this->merchatId . "&data=" . $encrypt_data;
        return ['success' => true, 'data' => ['url' => $loginUrl, 'method' => 1], 'message' => ''];
    }

    public function curlJoinMobileGame($request)
    {
        return $this->curlJoinGame($request);
    }


    //游戏抓单
    public function curlGetBetRecord(Carbon $startTime, Carbon $endTime)
    {
        $items = [];
        $page = 1;
        $url = $this->gameUrl . self::BETRECORD;
        $start_time = $startTime->format('Y-m-d\TH:i:s\Z');
        $end_time = $endTime->format('Y-m-d\TH:i:s\Z');

        do {
            $flag = false;
            $data = [
                "channelId" => -1,
                'startTime' => $start_time,
                'endTime' => $end_time,
                'isUpdateTime' => true,
                'state' => -1,
                'recordPage' => $page - 1,
                'recordCountPerPage' => 500
            ];

            $body = [
                "version" => $this->version,
                "id" => $this->merchatId,
                "data" => $this->apiEncode(json_encode($data))
            ];
            $output = $this->request('POST', $url, $body);
            $output = json_decode($this->apiDecode($output), true);
            if (array_key_exists('betRecords', $output)) {
                if (count($output['betRecords']) >= 1) {
                    $items = array_merge($items, $output['betRecords']);
                    $flag = true;
                }
            }
            $page++;
        } while ($flag);

        return $items;
    }
}